package com.example.administrator.newxlmedical;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.os.Message;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.example.administrator.baseproject.BaseActivity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import beans.AllDepts;
import beans.AllEmployee;
import beans.OperateGoodsDetailsBean;
import beans.PutAndDeleteBean;
import beans.TerminalBean;
import beans.Test;
import beans.TokenBean;
import beans.XLKJResult;
import constants.Constants;
import constants.HandlerConstant;
import netframe.GetRetrofit;
import netframe.MyAction1;
import netframe.NetAddress;
import netframe.NetReconnectFunc1;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.observables.GroupedObservable;
import rx.schedulers.Schedulers;
import serialport.SerialPortManager;
import sqlite.MyGoodsInfoSQLiteOpenHelper;
import utils.ActivityUtil;
import utils.HardwareInfoUtils;
import utils.NetUtil;
import utils.ObjectSaveUtil;
import utils.TimeUtil;
import utils.ToastUtil;

public class StartActivity extends BaseActivity {
    private ProgressDialog dialog;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor edit;
    private boolean isTerminal = true;
    private Context mContext;
    private SQLiteDatabase database;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
        mContext = this;
        Log.e(TAG, "onCreate: " + TimeUtil.getMillisecondDate() );
    }

    @Override
    public void initView() {
        sharedPreferences = ActivityUtil.getSharedPreferences(StartActivity.this);
        String apkName = sharedPreferences.getString(Constants.APK_NAME, "");
        //  版本更新会下载apk在本地，这里根据apk名称 删除安装包
        if (apkName != null && !apkName.equals("")){
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + apkName);
            if (file.exists()){
                file.delete();
            }
        }
        Constants.TIME_OUT = sharedPreferences.getInt(Constants.TIME_OUT_KEY,60000);
        Constants.EXIT = sharedPreferences.getInt(Constants.EXIT_KEY,60 * 60 * 8 * 1000);
        dialog = new ProgressDialog(StartActivity.this);
        dialog.setCanceledOnTouchOutside(false);
        init();
    }

    private void init() {
        if (NetUtil.isNetworkConnected(StartActivity.this)) {
            sendEmptyMessageDelay(HandlerConstant.NETWORK_CONNECT, 3000);
            dialog.setTitle("正在初始化...");
            dialog.show();
        } else {
            sendEmptyMessageDelay(HandlerConstant.NETWORK_NONE, 10000);
            dialog.setTitle("正在初始化...");
            dialog.show();
        }
    }

    @Override
    public void onHandleMessage(Message msg) {
        switch (msg.what) {
            case HandlerConstant.NETWORK_MOBILE:
            case HandlerConstant.NETWORK_WIFI:
            case HandlerConstant.NETWORK_ETHERNET:
            case HandlerConstant.NETWORK_CONNECT:
                if (!Constants.IS_FUYI) {
                    getAllDept();
                }
                isTerminal();
//                getDeptCode();
                break;
            case HandlerConstant.NETWORK_NONE:
                Constants.IS_NETWORK = false;
                dialog.setTitle("初始化失败，请检查网络");
                ToastUtil.showToast(StartActivity.this, "请检查网络");
                break;
            case HandlerConstant.NETWORK_REFRESH:
                Log.e("TAG", "onHandleMessage: NETWORK_REFRESH");
                init();
                break;
        }
    }

    public void isTerminal() {
        Log.e(TAG, "isTerminal: ");

        GetRetrofit.getRetrofit().getToken("select * from Token where MachineCode = '" + HardwareInfoUtils.getMachineCode(mContext) + "'").subscribeOn(Schedulers.io()).retryWhen(new NetReconnectFunc1()).groupBy(new Func1<List<TokenBean>, Boolean>() {
            @Override
            public Boolean call(List<TokenBean> tokenBeen) {
                return tokenBeen == null ? false : tokenBeen.size() != 0;
            }
        }).observeOn(AndroidSchedulers.mainThread()).onTerminateDetach().flatMap(new Func1<GroupedObservable<Boolean, List<TokenBean>>, Observable<TokenBean>>() {
            @Override
            public Observable<TokenBean> call(GroupedObservable<Boolean, List<TokenBean>> booleanListGroupedObservable) {
                if (booleanListGroupedObservable.getKey()) {
                    //已经被激活过，
                    return booleanListGroupedObservable.observeOn(Schedulers.io()).flatMap(new Func1<List<TokenBean>, Observable<TokenBean>>() {
                        @Override
                        public Observable<TokenBean> call(List<TokenBean> tokenBeen) {
                            return Observable.from(tokenBeen).last();
                        }
                    });
                } else {
                    Log.e(TAG, "call: 未激活");
                    //还没有被激活过
                    //为空说明还未被激活
                    dialog.dismiss();
                    ActivityUtil.jumpToActivity(StartActivity.this, TerminalActivity.class);
                    return null;
                }
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<TokenBean>() {
            @Override
            public void call(TokenBean tokenBean) {
                Log.e(TAG, "call: 已激活");
                NetAddress.token = tokenBean.getTokenCode();
                NetAddress.machineCode = tokenBean.getMachineCode();
                NetAddress.terminalInfoId = tokenBean.getTerminalInfoId() + "";
                getDeptCode();
            }
        }, new MyAction1() {
            @Override
            public void call(Throwable throwable) {
                super.call(throwable);
                ToastUtil.showToast(mContext, "网络请求错误");
            }
        });

    }

    /*
        协和 全部科室
     */

    private void getAllDept() {
        GetRetrofit.getInstance3().getDept().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<XLKJResult<AllDepts>>() {
                    @Override
                    public void call(XLKJResult<AllDepts> allDeptsXLKJResult) {
                        if (allDeptsXLKJResult.getResultCode() == 100) {
                            List<AllDepts> result = allDeptsXLKJResult.getResult();
                            if (result != null && result.size() != 0) {
                                // TODO: 病区 只留 4
                                ObjectSaveUtil.saveObject(StartActivity.this, result, Constants.ALL_DEPT, Constants.ALL_DEPT);

                            }
                        } else {
                            ToastUtil.showToast(StartActivity.this, allDeptsXLKJResult.getMsg());
                        }
                    }
                }, new MyAction1() {
                    @Override
                    public void call(Throwable throwable) {
                        super.call(throwable);
                        ToastUtil.showToast(StartActivity.this, throwable.getMessage());
                    }
                });
    }

    public void getDeptCode() {

        final SharedPreferences.Editor edit = sharedPreferences.edit();
        GetRetrofit.getInstance().getDeptCode("select * from TerminalInfo where ID =" + NetAddress.terminalInfoId)
                .enqueue(new Callback<ArrayList<TerminalBean>>() {
                    @Override
                    public void onResponse(Call<ArrayList<TerminalBean>> call, Response<ArrayList<TerminalBean>> response) {
                        ArrayList<TerminalBean> body = response.body();
                        if (body != null && body.size() != 0) {
                            TerminalBean terminalBean = body.get(0);
                            dialog.dismiss();
                            if (terminalBean != null) {
                                Log.e(TAG, "onResponse: " + terminalBean.getID());
                                NetAddress.deptCode = terminalBean.getDeptCode();
                                edit.putString(Constants.DEPARTMENT_CODE, terminalBean.getDeptCode());
                                edit.putString(Constants.HOSPITAL_NAME, terminalBean.getHospName());
                                edit.putString(Constants.HOSPITAL_ADDRESS, terminalBean.getAddress());
                                edit.putString(Constants.HOSPITAL_DEPARTMENTS, terminalBean.getDepartment());
                                edit.putString(Constants.HOSPITAL_REMARK, terminalBean.getReamrk());
                                edit.commit();

                            }
                            ActivityUtil.jumpToActivity(StartActivity.this, EnterActivity.class);
                            finish();
                        }
                    }

                    @Override
                    public void onFailure(Call<ArrayList<TerminalBean>> call, Throwable t) {
                            ToastUtil.showToast(StartActivity.this,"终端ID查询不到!");
                    }
                });
    }

}
